<script lang="ts" setup>
import router from '@/router'
import { tabStore } from '@/store/modules/tab'
import type { TabPaneName } from 'element-plus'
interface tabVo {
  path: string,
  label: string
}
const route = useRoute()
const store = tabStore()
const currentTab = ref('') // 当前路由（tab）
const tabList = ref<tabVo[]>([])
watch(store.getOpendTabs, (newV) => {
  tabList.value = newV
})
watch(() => store.getActivePath, (newV) => {
  currentTab.value = newV
})
watch(route, (to, from) => {
  // console.log('----路由变化：to = ', to)
  // 判断路由是否已经打开
  // 已经打开的 ，将其置为active
  // 未打开的，将其放入队列里
  console.log('tabList.value = ', tabList.value)
  const flag = ref(false)
  for (const item of tabList.value) {
    if (item.path === to.path) {
      store.setActivePath(to.path)
      flag.value = true
      if (to.query.id) {
        flag.value = false
      }
      break
    }
  }
  if (!flag.value) {
    const routerData = {
      path: to.path,
      label: to.name as string
    }
    store.addOpendTabs(routerData)
    store.setActivePath(to.path)
  }
})
onMounted(() => {
  //
  console.log('tabList.value = ', tabList.value)
  const flag = ref(false)
  for (const item of store.getOpendTabs) {
    if (item.path === route.path) {
      store.setActivePath(route.path)
      flag.value = true
      if (route.query.id) {
        flag.value = false
      }
      break
    }
  }
  if (!flag.value) {
    const routerData = {
      path: route.path,
      label: route.name as string
    }
    store.addOpendTabs(routerData)
    store.setActivePath(route.path)
  }
})
const addTab = (targetPath: TabPaneName) => {
  tabList.value.push({
    label: 'New Tab',
    path: targetPath as string
  })
  currentTab.value = targetPath as string
}
const tabClick = () => {
  router.push(`${currentTab}`)
}
const removeTab = (targetPath: TabPaneName) => {
  const tabarray = tabList.value
  const delIndex = tabarray.findIndex(val => {
    return val.path === targetPath
  })
  // 首页不删
  // if (targetPath === '/') {
  //   return
  // }
  store.deleteTab(delIndex)
  console.log(tabList.value[delIndex - 1], delIndex)
  if (currentTab.value === targetPath) {
    // 设置当前激活的路由
    if (tabList.value && tabList.value.length >= 1) {
      router.push({ path: tabList.value[delIndex - 1].path })
    } else {
      router.push({ path: '/' }) // 首页
    }
  }
}
</script>
<template>
  <div class="headTabs">
    <el-tabs
      v-model="currentTab"
      type="card"
      v-if="tabList.length>0"
      class="demo-tabs"
      closable
      @tab-click='tabClick'
      @tab-remove="removeTab"
    >
      <el-tab-pane
        v-for="item in tabList"
        :key="item.path"
        :label="item.label"
        :name="item.path"
      />
    </el-tabs>
  </div>
</template>
<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
